const i18n = require('../../i18n/index');

Page({
  data: {
    currentLang: 'zh-CN',
    l10n: {
      title: '',
      zhCN: '',
      zhHK: '',
      enUS: '',
      switchApplied: ''
    }
  },
  
  onLoad: function() {
    try {
      const saved = wx.getStorageSync('app:lang');
      if (saved) {
        this.setData({ currentLang: saved });
      }
    } catch (e) {}
    this.updateTexts();
  },

  onShow: function() {
    // 如果全局语言被其他页面改了，这里同步
    const lang = i18n.getLang();
    if (lang !== this.data.currentLang) {
      this.setData({ currentLang: lang });
      this.updateTexts();
    }
  },
  
  updateTexts: function() {
    const l10n = {
      title: i18n.t('language.title'),
      zhCN: i18n.t('language.zhCN'),
      zhHK: i18n.t('language.zhHK'),
      enUS: i18n.t('language.enUS'),
      switchApplied: i18n.t('language.switchApplied')
    };
    this.setData({ l10n });
    wx.setNavigationBarTitle({ title: l10n.title });
  },
  
  // 切换语言（保存 + 通知 + 提示）
  switchLanguage: function(e) {
    const lang = e.currentTarget.dataset.lang;
    if (lang === this.data.currentLang) {
      return;
    }

    this.setData({ currentLang: lang });
    try {
      i18n.setLang(lang);
    } catch (e) {}

    wx.showToast({
      title: i18n.t('language.switched'),
      icon: 'success',
      duration: 1200
    });

    // 立即刷新文案与导航标题
    this.updateTexts();

    setTimeout(() => {
      wx.navigateBack({ fail: () => {} });
    }, 1200);
  }
}); 